(function() {
  app.controller('runningCtrl', function($stateParams, $location, $scope, tradeApi, $state, $filter, $rootScope, quoteApi, local_m, $interval, header_m, $timeout) {
    header_m.set({
      css_l: {
        name: 'icon-user'
      },
      fun_l: function() {
        local_m
          .set('my_index_back', 'running');
        $state.go('my_index');
      },
      css_r: {
        name: 'refresh@2x'
      },
      fun_r: function() {
        $('#header_right').removeClass('reload-ate');
        $timeout(function() {
          $('#header_right').addClass('reload-ate');
        });
      }
    });

    $scope.formatDate = $filter('date')(new Date(), 'yyyy-MM-dd');
    $scope.running_tab_actived = $stateParams.tab_index || '1';
    var params = [{ total: '0' }, { today_create: '0' }, { total_sell: '0' }];

    $scope.reload = function() {
      tradeApi.query({
        funcId: '300026',
        data: params[$scope.running_tab_actived - 1]
      }).then(function(res) {
        $scope.result = res || [];
      });
    };

    $scope.go_detail = function(item, boolean) {
      if (item.contract_status === '2') return;

      local_m.set('running', item);
      $state.go('details');
    };

    $scope.change_tab = function(index) {
      $state.go('running', { tab_index: index }, 'reload');
      $location.replace();
    };

    var timer = $interval(function() {
      $scope.reload();
    }, 5000);

    $scope.$on('$destroy', function() {
      $interval.cancel(timer);
      timer = null;
    });

  });

  app.filter('zhixing_state', function($filter) {
    return function(input) {
      var arr = {
        1: { state: '已了结', color: 'red' },
        2: { state: '执行买入失败', color: 'red' },
        3: { state: '执行买入中', color: 'red' },
        4: { state: '执行买入成功', color: 'red' },
        5: { state: '今日到期', color: '#00aeef' },
        6: { state: '明日到期', color: '#00aeef' },
        7: { state: '延期申请中', color: '#00aeef' },
        8: { state: '执行卖出中', color: '#00aeef' },
        9: { state: '卖出成功待结算', color: '#00aeef' },
      };
      return arr[input];
    };
  });

  app.filter('retain_float', function($filter) {
    return function(input) {
      if (!input) return input;
      return parseFloat(input).toFixed(2);
    };
  });
})();